import java.math.BigInteger;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Created by IntelliJ IDEA.
 * User: caporegim
 * Date: 08.08.12
 * Time: 22:52
 * To change this template use File | Settings | File Templates.
 */
public class LockFreeFibonachiGenerator2 implements Fibonachi{
    private volatile  AtomicReference ref = new AtomicReference(new Pair());

    @Override
    public BigInteger next() {
        Pair value = ( Pair) ref.get();
        BigInteger result = value.getValue1().add(value.getValue2());
        Pair pair2 = new Pair(value.getValue2(), result);
        ref.compareAndSet(value, pair2);
        return result;
    }

    private  static final class Pair{
        private BigInteger value1 = new BigInteger("0");
        private BigInteger value2 = new BigInteger("1");

        private Pair() {
        }

        private Pair(BigInteger value1, BigInteger value2) {
            this.value1 = value1;
            this.value2 = value2;
        }

        public BigInteger getValue1() {
            return value1;
        }

        public BigInteger getValue2() {
            return value2;
        }
    }

}
